package com.stedu.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.stedu.bean.Admin;
import com.stedu.exception.SteduException;
import com.stedu.mapper.AdminMapper;
import com.stedu.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {
     @Autowired
    private AdminMapper adminMapper;
    @Override
    public Admin login(String username, String password ,String user) throws SteduException {
        //调用dao的方法



        Admin admin = adminMapper.selectByUsername(username,user);
            if (admin == null){
                throw new SteduException("用户名错误请确认后重新登录");
            }

        //对用户输入的密码进行俩次加密
        String md5paw = SecureUtil.md5(SecureUtil.md5(password));
        if (!md5paw.equals(admin.getPassword())){
            throw new SteduException("密码错误请确认后重新登录");

        }
        return admin;
    }


    @Override
    public List<Map<String, Object>> selectTop5DnameAndCount() {
        return adminMapper.selectTop5DnameAdCount();
    }

    @Override
    public boolean insert(Admin a) throws SteduException {

        if (a.getUsername()==""||a.getUsername()==null){

            throw new SteduException("用户名不能为空");
        }
        else if(adminMapper.selectUsername(a.getUsername())!=null )
        {
            //抛出自定义异常
            throw new SteduException("该用户名已经存在，无法注册");
        }else{
            a.setUser("用户");
            String md5paw = SecureUtil.md5(SecureUtil.md5(a.getPassword()));
            a.setPassword(md5paw);
            return adminMapper.insert(a)==1;
        }

    }

    @Override
    public boolean delete(Integer id) throws SteduException {
        return adminMapper.delete(id)==1;
    }

    @Override
    public boolean update(Admin a) throws SteduException {
        if (a.getUsername()==null||a.getUsername()==""){
            throw new SteduException("用户名不能为空");
        }
        else   if(adminMapper.selectUsername(a.getUsername())!=null )
        {
            //抛出自定义异常
            throw new SteduException("该用户名已经存在，无法修改");
        }
        String md5paw = SecureUtil.md5(SecureUtil.md5(a.getPassword()));
        a.setPassword(md5paw);
        return adminMapper.update(a)==1;
    }

    @Override
    public Integer selectuserNumber() {
        return adminMapper.selectuserNumber();
    }


    @Override
    public Admin selectById(Integer id) {
        return adminMapper.selectById(id);
    }

    @Override
    public Admin selectUsername(String username) {
        return adminMapper.selectUsername(username);
    }

    @Override
    public List<Admin> selectPage(String uname) {
        return adminMapper.selectPage(uname);
    }

}
